/*
* navigator.language, // 浏览器指定的语言
* navigator.platform, // 操作系统类型
* navigator.onLine, // 是否在线
* navigator.hardwareConcurrency, // 硬件并发性
* navigator.maxTouchPoints // 最大触摸点数
*/
var userAgent = navigator.userAgent.toLowerCase();
let device = `${navigator?.appName}_${navigator.appVersion}_${navigator.userAgent}`
let systemInformation = `${navigator.language}_${navigator.platform}_${navigator.onLine}_${navigator.hardwareConcurrency}_${navigator.maxTouchPoints}`
let address = '';

var browser = {
    versions: function () {
        var u = navigator.userAgent,
            app = navigator.appVersion;
        return { //移动终端浏览器版本信息
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
            iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
        };
    }(),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
}
const params = new URLSearchParams(window.location.search);

// 滚动到元素到另一个元素
function scrollToElement(targetId) {
    var targetOffset = $(`${targetId}`).offset().top;
    var referenceOffset = $('html').offset().top;
    $('html').get(0).scrollTo({
        top: targetOffset - referenceOffset,
        behavior: 'smooth'
    });
}

/*
*type：‘browse’
*common(外部链接)、browse（浏览）、download_daka_android、download_daka_ios、download_lele_android、download_lele_ios、download_yule_android、download_yule_ios
*device: 设备类型
*browser：浏览器类型
*access_source： 不传
*behavior：link_优酷文化(路由调整)（内部页面 browse）、common_备案号(外部页面 type：common)、swiper_产品展示捕鱼大咖
*address：用户地址、拿不到传''
*/
function postOfficialwebsitelogLog(type, behavior, gameType = '') {
    console.log({ behavior, type })
    $.ajax({
        // url: 'http://192.168.1.187:56146/officialwebsitelog/log',
        url: 'https://api-userappeal-bydk-q15a.youxinhuyu.cn:56146/officialwebsitelog/log',
        type: 'POST',
        contentType: 'application/json; charset=UTF-8', // 修改为你需要的content-type
        dataType: 'json',
        data: JSON.stringify({
            browser: systemInformation, // 系统信息
            device: device, // 浏览器信息
            address: address, // 地理位置
            access_source: '', // 来源
            behavior: behavior, // 行为
            types: type,
            game_type: gameType, // buyudaka、lelebuyu、yuledaren
        }), // 如果发送JSON数据，需要将对象转换为字符串
        success: function (response) {
            // 请求成功时的回调函数
        },
        error: function (xhr, status, error) {
            // 请求失败时的回调函数
        }
    });
}

// 关闭 提示浏览器打开的弹框
function DownloadGuideRemove() {
    $('#DownloadGuide').remove();
}

// 游戏下载的公用方法
function download(downloadType = params.get('type'), gameType = params.get('gameType')) {
    if (userAgent.indexOf('micromessenger') !== -1) {
        $("body").append(`<div id="DownloadGuide" onclick="DownloadGuideRemove()"></div>`)
    } else if (browser.versions.ios || browser.versions.iPhone || browser.versions.iPad) {
        postOfficialwebsitelogLog(`download_${downloadType}_ios`, `download_${downloadType}_ios`, gameType);
        if (downloadType === 'buyudaka') {
            window.location = "https://apps.apple.com/cn/app/id1561105019";
        } else if (downloadType === 'lelebuyu') {
            window.location = "https://itunes.apple.com/cn/app/id1489278985?mt=8";
        } else if (downloadType === 'yuledaren') {
            window.location = "https://itunes.apple.com/cn/app/id1665337957?mt=8";
        }
    } else {
        postOfficialwebsitelogLog(`download_${downloadType}_android`, `download_${downloadType}_android`, gameType);
        if (downloadType === 'buyudaka') {
            window.location = "https://dl01bydk.youxinhuyu.cn/onlineapk/guanwang02.apk";
        } else if (downloadType === 'lelebuyu') {
            window.location = "https://dl01lele.youxinhuyu.cn/u3dlelejieji/guanwang02.apk";  //安卓跳转链接
        } else if (downloadType === 'yuledaren') {
            window.location = "https://dl01yldr.youxinhuyu.cn/yldrapk/guanwang02.apk";  //安卓跳转链接
        }

    }
    //            document.writeln("语言版本: " + browser.language);
    //            document.writeln(" 是否为移动终端: " + browser.versions.mobile);
    //            document.writeln(" ios终端: " + browser.versions.ios);
    //            document.writeln(" android终端: " + browser.versions.android);
    //            document.writeln(" 是否为iPhone: " + browser.versions.iPhone);
    //            document.writeln(" 是否iPad: " + browser.versions.iPad);
    //            document.writeln(navigator.userAgent);
}

// 返回顶部的按钮
function BackToTop() {
    var windowHeight = $(window).height();
    var scrollPosition = $('html').scrollTop();
    if (scrollPosition > windowHeight) {
        if (!$('.BackToTop').length) $("body").append(`<div class="BackToTop" onclick="scrollToElement('html')"><img src="https://webfiledata.66y.com/guanwang/images/BackToTop.png" alt=""></div>`);
    } else {
        $('.BackToTop').remove();
    }
}

// 横屏后竖屏提示
function rotatingScreen() {
    var orientation = window.orientation;
    var pd = null;
    function createPd() {
        if (document.getElementById('preventTran') === null) {
            var imgData = '';
            pd = document.createElement('div');
            pd.setAttribute('id', 'preventTran');
            pd.style.position = 'fixed';
            pd.style.left = '0';
            pd.style.top = '0';
            pd.style.width = '100%';
            pd.style.height = '100%';
            pd.style.overflow = 'hidden';
            pd.style.backgroundColor = '#2e2e2e';
            pd.style.textAlign = 'center';
            pd.style.zIndex = '99999';
            document.getElementsByTagName('body')[0].appendChild(pd);
            var img = document.createElement('img');
            img.src = imgData;
            pd.appendChild(img);
            img.style.margin = '60px auto 30px'
            var br = document.createElement('br');
            var p = document.createElement('p');
            p.style.width = '100%';
            p.style.height = 'auto';
            p.style.fontSize = '22px';
            p.style.color = '#626262';
            p.style.lineHeight = '34px';
            p.style.textAlign = 'center';
            p.innerHTML = '为了您的良好体验';
            p.appendChild(br);
            p.innerHTML += '请将手机/平板竖屏操作';
            pd.appendChild(p);
        }
    }
    if (orientation == 90 || orientation == -90) {
        if (pd == null && document.getElementById('preventTran') === null) createPd();
        document.getElementById('preventTran').style.display = 'block';
    }
    window.onorientationchange = function () {
        if (pd == null && document.getElementById('preventTran') == null) createPd();
        document.getElementById('preventTran').style.display = 'none';
        rotatingScreen();
    };
}

function imgLazyLoad() {
    // 1 获取全部图片的DOM节点
    // 注意：querySelectorAll 值为伪数组利用扩展运算符转为真数组
    const images = [...document.querySelectorAll('img[data-src]'), ...document.querySelectorAll('.lazy_bg[data-src]')]

    // 2 监听页面滚动事件
    window.addEventListener('scroll', lazyLoad)

    // 3 定义页面滚动的处理函数
    function lazyLoad() {
        for (let i = 0; i < images.length; i++) {
            // isVisible是否该图片位于可视区域 返回true 或false
            if (isVisible(images[i])) {
                // 将元素的自定义属性 data-src 赋值给元素的 src 属性 
                // dataset.src 此为元素的自定义属性 data-src
                if (images[i].classList.contains('lazy_bg')) {
                    images[i].style.backgroundImage = `url(${images[i].dataset.src})`;
                } else if (!images[i].src) {
                    images[i].src = images[i].dataset.src;
                }
                // 等价于：img.setAttribute('src', img.getAttribute('data-src'))
                // 防止重复被遍历 加载完之后 删除元素不再加载
                images.splice(i, 1)
                i--
            }
        }
    }
    lazyLoad()

    // 4 可视区域判断函数
    function isVisible(img) {
        // 判断是否在可视区域
        const imgRect = img.getBoundingClientRect() // getBoundingClientRect 获取图片的动态信息
        return imgRect.bottom > 0 && imgRect.top < window.innerHeight
    }
}


function domWindowScale() {
    const observer = new ResizeObserver(windowScale);
    observer.observe($('.windowScale')[0]);
    $(window).resize(windowScale);
    windowScale();
}

// fn只执行一次
$.once = function (fn) {
    var executed = false; // ⽅法执⾏状态，默认为未执⾏
    var onceFn = function () {
        if (!executed) {
            fn.apply(this, arguments);
            executed = true; // 更新⽅法执⾏状态为已执⾏
        }
    };
    onceFn.isExecuted = function () {
        return executed; // 返回⽅法执⾏状态
    };
    return onceFn;
};

// 监听windowScale的宽高变化
const windowScaleResize = $.once(() => {
    const observer = new ResizeObserver(windowScale);
    observer.observe($('.windowScale')[0]);
})

// 计算宽度 transform 缩放适应屏幕
function windowScale() {
    const viewportWidth = $(window).width();
    const viewportHeight = $(window).height();
    const windowScaleFaEl = $('.windowScaleFa');
    const windowScaleEl = $('.windowScale');
    const windowScaleWidth = windowScaleEl.outerWidth();
    const windowScaleHeight = windowScaleEl.outerHeight();
    const scale = viewportWidth / windowScaleWidth;

    const translateXCalculation = (windowScaleWidth - viewportWidth) / 2 / scale;
    const translateX = scale < 1 ? -translateXCalculation : Math.abs(translateXCalculation);
    const translateY = ((windowScaleHeight * scale) - windowScaleHeight) / 2 / scale;
    windowScaleEl.css({ 'transform': `scale(${scale}) translateX(${translateX}px) translateY(${translateY}px)` });
    windowScaleFaEl.css({ 'width': `${viewportWidth}px`, 'height': `${windowScaleHeight * scale}px`, 'overflow': 'hidden' });     
    windowScaleResize();
}

// 匹配设备宽高 设置class
function detectType() {
    const viewportWidth = $(window).width();
    const viewportHeight = $(window).height();
    if (viewportWidth > 767 && 1 > (viewportWidth / viewportHeight) && (viewportWidth / viewportHeight) > 0.6) {
        $("body").removeClass("equipmentMobile");
        $("body").removeClass("equipmentPC");
        $("body").addClass("equipmentTablet");
        return 'Tablet';
    } else if (viewportHeight > viewportWidth) {
        $("body").removeClass("equipmentTablet");
        $("body").removeClass("equipmentPC");
        $("body").addClass("equipmentMobile");
        return 'Mobile';
    } else {
        $("body").removeClass("equipmentTablet");
        $("body").removeClass("equipmentMobile");
        $("body").addClass("equipmentPC");
        return 'PC'
    }
}